<?php
include('../../admin/php/bootstrap.php');
/*$randomIds = array();
$ids = Doctrine_Query::create()
        ->select('p.id')
        ->from('Publicidad p')
        ->innerJoin('p.tipo t WITH t.id = ?', $_POST['id'])
        ->where('p.id_estado = '.Estado::VISIBLE)
        ->execute(array(), Doctrine::HYDRATE_SINGLE_SCALAR)
;
if (!is_array($ids)) $ids = array($ids);

while ($_POST['cantidad']--) {
    if (count($ids)) {
        $i = rand(0, count($ids)-1);
        $randomIds[] = $ids[$i];
        unset($ids[$i]);
        $ids = array_values($ids);
    }
}


if (count($randomIds)) {
    $publiciadades = Doctrine_Query::create()
            ->select('p.id as id, p.src as src, p.url as url')
            ->from('Publicidad p')
            ->whereIn('p.id', $randomIds)
            ->execute(array(), Doctrine::HYDRATE_ARRAY)
    ;
} else {
    $publiciadades = array();
}*/

$q = Doctrine_Query::create()
        ->select('p.id, p.url, p.src')
        ->from('Publicidad p')
        ->innerJoin('p.tipo t')
        ->orderBy('p.orden')
;
if ($_POST['id']==2) {
    $q->where('(t.id >= 2 and t.id <=3 and p.id_estado = ?)', Estado::VISIBLE);
} else {
    $q->where('(t.id = ? and p.id_estado = ?)', array($_POST['id'], Estado::VISIBLE));
}
//if (isset($_POST['publicacion'])) $q->innerJoin('p.publicaciones pb WITH pb.id = ?', $_POST['publicacion']);

if (isset($_POST['publicacion']))$q->leftJoin('p.publicaciones pb');
if (isset($_POST['categoria'])) $q->leftJoin('p.categorias c');

if (isset($_POST['publicacion']) && isset($_POST['categoria'])) {
    $q->andWhere('(pb.id = ? or c.slug = ?)', array($_POST['publicacion'], $_POST['categoria']));
} else if (isset($_POST['publicacion'])) {
    $q->andWhere('(pb.id = ?)', array($_POST['publicacion']));
} else if (isset($_POST['categoria'])) {
    $q->andWhere('(c.slug = ?)', array($_POST['categoria']));
}

//echo($q->getSqlQuery());exit();
$publiciadades = $q->execute(array(), Doctrine::HYDRATE_ARRAY);
header("Content-type: application/json");
echo(json_encode($publiciadades));
?>
